package com.lcicl.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lcicl.reggie.common.R;
import com.lcicl.reggie.entity.Category;
import com.lcicl.reggie.entity.Dish;
import com.lcicl.reggie.entity.DishFlavor;
import com.lcicl.reggie.entity.dto.DishDto;
import com.lcicl.reggie.service.CategoryService;
import com.lcicl.reggie.service.DishFlavorService;
import com.lcicl.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/*
  Date: 2023/08/10
  Author: Luochao
  Description:
        菜品管理
*/

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 分页查询菜品
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> rePage = new Page<>();

        //查询对象
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo, queryWrapper);

        BeanUtils.copyProperties(pageInfo, rePage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> lst = null;

        lst = records.stream().map((item) -> {       //获取每个DishDto的categoryName
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long cateGoryId = item.getCategoryId();
            Category category = categoryService.getById(cateGoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);

            return dishDto;
        }).collect(Collectors.toList());

        rePage.setRecords(lst);

        return R.success(rePage);
    }

    /**
     * 修改菜品数据回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getOne(@PathVariable(value = "id") Long id) {

        DishDto dishDto = new DishDto();

        Dish dish = dishService.getById(id);
        BeanUtils.copyProperties(dish, dishDto);

        //查询口味
        Long dishId = dish.getId();
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishId);
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);

        //查询该菜品分类
        Long categoryId = dishDto.getCategoryId();
        String categoryName = categoryService.getById(categoryId).getName();
        dishDto.setCategoryName(categoryName);


        return R.success(dishDto);
    }

    /**
     * 根据菜品分类查询
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> collect = null;


        String key = "dish:" + dish.getCategoryId() + ":" + dish.getStatus();
        //从rides中获取菜品缓存数据
        collect = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //存在则直接返回
        if (collect != null) {
            return R.success(collect);
        }

        //不存在则查询
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .eq(dish.getStatus() != null, Dish::getStatus, dish.getStatus());
        List<Dish> dishes = dishService.list(queryWrapper);


        collect = dishes.stream().map(rDish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(rDish, dishDto);
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, rDish.getId());

            List<DishFlavor> flavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(flavors);

            return dishDto;
        }).collect(Collectors.toList());

        //加入缓存
        redisTemplate.opsForValue().set(key, collect, 60, TimeUnit.MINUTES);


        return R.success(collect);
    }

    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping()
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);

        //跟新缓存
        String key = "dish:" + dishDto.getCategoryId() + "*";
        redisTemplate.delete(key);

        return R.success("添加成功");
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping()
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);

        Set keys = redisTemplate.keys("dish:" + dishDto.getCategoryId() + ":*");
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping()
    public R<String> delete(@RequestParam(name = "ids", required = true) ArrayList<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            if (dish.getStatus() == 1) {        //起售时禁止删除
                return R.error("起售时禁止删除");
            }
        }

        ids.forEach(id->{
            Dish dish = dishService.getById(id);
            Set keys = redisTemplate.keys("dish:" + dish.getCategoryId() + ":*");
            redisTemplate.delete(keys);
        });
        dishService.removeDish(ids);



        return R.success("删除成功");
    }

    /**
     * 启用&禁用
     *
     * @param status
     * @param longs
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable(value = "status") Integer status,
                            @RequestParam(name = "ids", required = true) ArrayList<Long> longs) {
/*        for (Long id : longs) {
            LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Dish::getId, id).set(Dish::getStatus, status);

            dishService.update(updateWrapper);

        }*/

        longs.stream().forEach((item) -> {
            LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Dish::getId, item).set(Dish::getStatus, status);
            dishService.update(updateWrapper);
        });

        return R.success("修改成功");
    }


}
